#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>

int main()
{
	while(1)
	{
		char line[128];
		printf("> ");
		fflush(stdout);
		fgets(line,sizeof(line),stdin);
		line[strlen(line)-1] = '\0';
		//printf("%ld ",strlen(line));
		//printf("%s\n",line);
		
		char *argv[16] = {NULL};
		int i = 0;
		char *word = strtok(line," ");
		while(word != NULL)
		{
			argv[i] = (char *)malloc(strlen(word));
			strcpy(argv[i],word);
			word = strtok(NULL," ");
			i+=1;
		}
		argv[i] = NULL;

		pid_t pid = fork();
		int a = strcmp(argv[0],"cd");
		int b = strcmp(argv[0],"pwd");
		int c = strcmp(argv[0],"exit");
		//printf("%d %d %d\n",a,b,c);

		if(argv[0] == NULL)
		{
			return 0;
		}
		if(pid < 0)
		{
			return -1;
		}
		else if(pid == 0)
		{
			if(a != 0 && b != 0 && c != 0)
			{
				//printf("in child\n");
				int error = execvp(argv[0],argv);
				return 127;
			}
			return 0;
		}
		else
		{
			//printf("in father\n");
			int status;
			wait(&status);
			if(!(WIFEXITED(status))) return -1;
			//printf("a:%d b:%d c:%d",a,b,c);
			if(a == 0)
			{
				//printf("in a\n");
				chdir(argv[1]);
				continue;
			}
			if(b == 0)
			{
				//printf("in b\n");
				char path[128];
				getcwd(path,sizeof(path));
				printf("%s\n",path);
				continue;
			}
			if(c == 0)
			{
				//printf("in c\n");
				return 0;
			}
		}
	}
	return 0;
}
